import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Modal, Form, Input, message as msg } from 'antd';

@connect(({ dictIndex, loading }) => ({
  modal: dictIndex.modal,
  submitting: loading.effects['dictIndex/update'],
}))
@Form.create()
class DictIndexModal extends PureComponent {
  handleModalCancel = () => {
    const { dispatch, form } = this.props;
    form.resetFields();
    dispatch({ type: 'dictIndex/closeModal' });
  };

  handleModalOk = () => {
    const { form, dispatch, onSubmit } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        dispatch({ type: 'dictIndex/update', payload: values }).then(({ code, message }) => {
          if (code === 0) {
            msg.success('操作成功');
            this.handleModalCancel();
            if (onSubmit) onSubmit(values);
          } else {
            msg.error(message);
          }
        });
      }
    });
  };

  render() {
    const {
      form,
      modal: { data, visible },
      submitting,
    } = this.props;
    const title = data.id ? '更新索引' : '添加索引';
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 15 },
    };
    return (
      <Modal
        title={title}
        visible={visible}
        confirmLoading={submitting}
        onCancel={this.handleModalCancel}
        onOk={this.handleModalOk}
      >
        {form.getFieldDecorator('id', { initialValue: data.id })}
        <Form.Item label="名称" {...formItemLayout}>
          {form.getFieldDecorator('name', {
            rules: [
              {
                type: 'string',
                required: true,
                message: '名称不能为空！',
              },
            ],
            initialValue: data.name,
          })(<Input />)}
        </Form.Item>
        <Form.Item label="编码" {...formItemLayout}>
          {form.getFieldDecorator('code', {
            rules: [
              {
                type: 'string',
                required: true,
                message: '编码不能为空！',
              },
            ],
            initialValue: data.code,
          })(<Input />)}
        </Form.Item>
        <Form.Item label="分组" {...formItemLayout}>
          {form.getFieldDecorator('groupCode', {
            rules: [
              {
                type: 'string',
                required: false,
              },
            ],
            initialValue: data.groupCode,
          })(<Input />)}
        </Form.Item>
      </Modal>
    );
  }
}

export default DictIndexModal;
